package com.wdd.libhttp.http


import com.wdd.libhttp.bean.ResultData
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 *
 * @ProjectName:    OwnTool
 * @Package:        com.wdd.libbase.http
 * @ClassName:      CommonObserver
 * @Description:     java类作用描述
 * @Author:         王丹丹
 * @CreateDate:     2019/12/5 11:32
 * @UpdateUser:     更新者
 * @UpdateDate:     2019/12/5 11:32
 * @UpdateRemark:   更新说明
 * @Version:        1.0
 */
abstract class CommonObserver<T> constructor(private var type: Type?) : Observer<String> {

    constructor() : this(null)

    override fun onSubscribe(d: Disposable) {
    }

    override fun onNext(str: String) {
        val convert: JsonConvert<T>?
        if (type == null) {
            val genType = javaClass.genericSuperclass
            type = (genType as ParameterizedType?)!!.actualTypeArguments[0]
            convert = JsonConvert(type)
        } else {
            convert = JsonConvert(type)
        }
        val data = convert.convertResponse(str)
        if (data is ResultData<*>) {
            val code = data.code
            if (code == 1) {
                onSuccessData(data)
            } else {
                onFailData(data.message!!)
            }

        } else {
            onSuccessData(data)
        }
    }

    override fun onError(e: Throwable) {
        e.printStackTrace()
    }

    /**
     * 成功方法的回调
     */
    abstract fun onSuccessData(mData: T)

    /**
     * 失败方法的回调
     */
    abstract fun onFailData(message: String)
}